<?php

namespace app\admin\service;


use app\admin\model\DeviceImei;
use app\admin\model\DeviceLocation;

/**
 * 设备轨迹管理-服务类
 * Class DeviceLocationService
 * @package app\admin\service
 */
class DeviceLocationService extends BaseService
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new DeviceImei();
    }

    public function info()
    {
        $imei = request()->param("imei", 0);
        if (empty($imei)) {
            return message("imei不能为空", false);
        }

        $field = [
            'i.imei',
            'i.is_active',
            'i.electricity_level',
            'stu.name' => 'stu_name',
            'stu.student_no',
            'stu.phone' => 'stu_phone',
        ];
        $info = $this->model->alias('i')
            ->leftJoin('student stu', 'i.imei = stu.imei')
            //->leftJoin('device_location location', 'i.imei = location.imei')
            ->where('i.imei', $imei)
            ->field($field)
            ->find();
        if (!empty($info)) {
            $info = $info->toArray();



            if(!empty(input('date_time'))){
                $map2 = [];
                $t1 = strtotime(input('date_time'));
                $t2 = $t1+24*3600;
                $map2[] = ['startTime',['>',$t1],['<',$t2]];
                $location = DeviceLocation::where('imei', $imei)
                    ->where($map2)
                    ->field('lng,lat,address,create_time')
                    ->order('id', 'desc')
                    ->find();
            }else{
                $location = DeviceLocation::where('imei', $imei)
                    ->field('lng,lat,address,create_time')
                    ->order('id', 'desc')
                    ->find();
            }

            if ($location) {
                $info = array_merge($info,$location->toArray());
                $imeiInfo = getImeiInfo($imei);
                 //print_r($imeiInfo);
                $info['is_active'] = $imeiInfo['online'];
                $info['electricity_level'] = $imeiInfo['battery'];
            }

        }
        //print_R($info);

        return message("操作成功", true, $info);
    }
}

